import base64
import pickle

from django_redis import get_redis_connection


def merge_cart_cookie_to_redis(request, user, response):
    """
    登录后合并cookie购物车数据到Redis
    :param request: 本次请求对象 获取cookie中的数据
    :param user: 登录用户信息 获取用户id
    :param response: 本次响应对象 清除cookie数据
    :return:
    """
    # 1 获取cookie的购物车数据
    cart_cookie = request.COOKIES.get("cart")
    # 2 如果没有数据 返回response
    if not cart_cookie:
        return response
    # 3 把数据解码为字典
    cookie_cart_dict = pickle.loads(base64.b64decode(cart_cookie.encode()))
    # 4 把购物车字典数据转为redis中保存到数据格式
    new_cart_dict = {}
    new_cart_selected_add = []
    new_cart_selected_rm = []
    for sku_id, cookie_value_dict in cookie_cart_dict.items():
        new_cart_dict[sku_id] = cookie_value_dict["count"]
        # print(cookie_value_dict)
        if cookie_value_dict["selected"]:
            new_cart_selected_add.append(sku_id)
        else:
            new_cart_selected_rm.append(sku_id)
    # 5 把转完格式的数据保存到redis hash
    redis_conn = get_redis_connection("carts")
    pl = redis_conn.pipeline()
    # 这里不会删除原来的数据 只会覆盖
    pl.hmset("cart_%s" % user.id, new_cart_dict)
    # 6 修改是否选中商品的状态
    if new_cart_selected_add:
        pl.sadd("selected_%s" % user.id, *new_cart_selected_add)
    if new_cart_selected_rm:
        pl.srem("selected_%s" % user.id, *new_cart_selected_rm)
    pl.execute()
    # 7 删除cookie数据
    response.delete_cookie("cart")
    # 8 返回响应
    return response
